package com.book.shop.Webservice;

import com.book.shop.model.Order;
import com.book.shop.model.Roles;
import com.book.shop.model.User;
import com.book.shop.repository.OrderRepository;
import com.book.shop.repository.UserRepository;
import com.book.shop.repository.RolesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private RolesRepository rolesRepository;
    @Autowired
    private OrderRepository orderRepository;

    //通过用户名查找用户
    public User findByUserName(String userName){
        return userRepository.findByUserName(userName);
    }
    //注册用户
    public User registerUser(User user){
        User newUser = new User();
        Optional<Roles> role_user = rolesRepository.findById("ROLE_USER");
        Roles role = role_user.get();
        Set<Roles> roles = new HashSet<>();
        BCryptPasswordEncoder encryptedPassword = new BCryptPasswordEncoder();
        String encode = encryptedPassword.encode(user.getUserPassword());
        newUser.setUserName(user.getUserName());
        newUser.setUserPassword(encode);
        newUser.setUserFullname(user.getUserFullname());
        newUser.setUserPhone(user.getUserPhone());
        newUser.setUserAddress(user.getUserAddress());
        newUser.setUserBankcard(user.getUserBankcard());
        roles.add(role);
        newUser.setRoles(roles);
        userRepository.save(newUser);
        return newUser;
    }
//    public User createUser(UserForm userForm){
//        User user = userForm.toUser();
//        return user;
//    }
   //更新用户信息
   public void updateUser(User user){
        User updateUser = userRepository.findById(user.getUserId()).get();
        updateUser.setUserFullname(user.getUserFullname());
        updateUser.setUserAddress(user.getUserAddress());
        updateUser.setUserPhone(user.getUserPhone());
        updateUser.setUserBankcard(user.getUserBankcard());
        userRepository.save(updateUser);
   }
   //查找所有用户信息
   public List<User> findAllUsers(){
        return userRepository.findAll();
   }
    //通过id查找
   public User findUserById(Long userId){
        return userRepository.findById(userId).get();
   }
    //通过用户id删除
    public void deleteUserById(Long userId){
        userRepository.deleteById(userId);
    }
    //查询用户对应的订单数量，有订单号的用户不允许删除
   public int getUserOrderAmount(Long userId){
       List<Order> order = orderRepository.findByUserId(userId);
       if(order==null){
           return 0;
       }
       else {
           return order.size();

       }
   }

}
